const connection = require('../app/database');

class OpusService {

  // 创建一个作品
  async create(userId, opusKey, opusValue, opusLink) {
    try {
      const statement = `INSERT INTO opus (user_id, opus_key, opus_value, opus_link) VALUES (?, ?, ?, ?)`;
      const result = await connection.execute(statement, [userId, opusKey, opusValue, opusLink]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一个作品
  async remove(userId, opusId) {
    try {
      const statement = `DELETE FROM opus WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [userId, opusId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 修改一个作品
  async update(userId, opusId, opusKey, opusValue, opusLink) {
    try {
      const statement = `UPDATE opus SET opus_key = ?, opus_value = ?, opus_link = ? WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [opusKey, opusValue, opusLink, userId, opusId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取作品列表
  async list(userId) {
    try {
      const statement = `
                  SELECT 
                    o.id 'key', 
                    o.user_id userId,
                    o.opus_key opusKey,
                    o.opus_value opusValue, 
                    o.opus_link opusLink,
                    o.createAt createTime
                  FROM opus o
                  WHERE user_id = ?
                `;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

}

module.exports = new OpusService();
